<template>
  <div class="login">
    <div class="login-container">
      <h1>登录</h1>
      <form
        ref="formRef"
        @submit.prevent="handleSubmit"
      >
        <input
          type="email"
          required
          placeholder="输入你的邮箱"
          v-model="form.email"
        />
        <input
          type="password"
          required
          placeholder="输入你的密码"
          v-model="form.password"
        />
        <router-link class="register-link" to="/register">还没有账号？去注册</router-link>
        <button>登录</button>
        <div class="error">{{error}}</div>
      </form>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue'
  import { loginForm, postLogin } from 'src/services/auth'
  import { useStore } from 'vuex'
  import {useRouter } from 'vue-router'
  import { SET_USER } from 'src/store/constants'
  export default defineComponent({
    setup () {
      const formRef = ref<HTMLFormElement | null>(null)

      const form = reactive<loginForm>({
        email: '',
        password: ''
      })
      const store = useStore()
      const router = useRouter()
      const error = ref('')
      const handleSubmit = async () => {
        const result = await postLogin(form)
        if (result.msg === 'success') {
          store.commit(SET_USER, result.data)
          router.push("/")
        } else {
          error.value = '邮箱或密码不正确'
        }
      }

      return {
        formRef,
        form,
        handleSubmit,
        error
      }
    }
  })
</script>

<style lang="scss" scoped>
  .login {
    height: calc(100vh - 110px);
  }
  .login-container {
    max-width: 400px;
    margin: 0 auto;
  }
  h1 {
    margin-bottom: 32px;
    text-align: center;
  }
  input {
    display: block;
    height: 42px;
    width: 100%;
    margin-bottom: 25px;
    padding-left: 1em;
    border: 1px solid #003371;
    outline: none;
    border-radius: 5px;
  }
  input:focus {
    border-color: #424C50;
  }
  input::placeholder {
    font-size: 14px;
    color: rgba($color: #758A99, $alpha: .9);
  }
  a {
    font-size: 14px;
    color: #2E4D7E;
  }
  button {
    display: block;
    width: 100%;
    height: 36px;
    margin-top: 5px;
    outline: none;
    border: 1px solid #003371;
    background-color: transparent;
    text-align: center;
    line-height: 34px;
    cursor: pointer;
  }
  .error {
    margin-top: 14px;
    text-align: center;
    font-size: 14px;
    color: crimson;
  }
</style>